package com.maple.excel.listeners;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONObject;
import com.maple.excel.entity.CustomerInfoBatch;
import com.maple.excel.utils.ValidatorUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>客户信息表格导入监听器</p>
 *
 * @author maple
 */
@Slf4j
public class CustomerInfoExcelListener extends AnalysisEventListener<CustomerInfoBatch> {

    private static final int BATCH_COUNT = 3000;

    private List<CustomerInfoBatch> data = new ArrayList<>(BATCH_COUNT);

    public CustomerInfoExcelListener() {
    }

    @Override
    public void invoke(CustomerInfoBatch newRawCustomer, AnalysisContext analysisContext) {
        data.add(newRawCustomer);

        if (data.size() >= BATCH_COUNT) {
            saveData();
            data = new ArrayList<>(BATCH_COUNT);
        }
    }

    /**
     * 这里能获取首行数据
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("解析到一条头数据:{}", JSONObject.toJSONString(headMap));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!data.isEmpty()) {
            saveData();
        }
        log.info("解析Excel数据完成.");
    }

    /**
     * 存储到数据库
     */
    private void saveData() {
        for (CustomerInfoBatch item : data) {
            log.info("item:{}", JSONObject.toJSONString(item));
            try {
                ValidatorUtil.validate(item);
            } catch (Exception e) {
                log.error("在线派单导入失败", e);
            }
        }
    }
}
